import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from 'views/Layout'
import Home from 'views/Home'
import Login from "views/Login";
Vue.use(VueRouter)


const routes = [{
    path: "*",
    component: () => import("views/404")
  },
  {
    path: "/login",
    name: "login",
    component: Login
  },
  {
    path: "/reg",
    name: "reg",
    component: () => import("views/Register")
  }, {
    path: '/',
    component: Layout,
    children: [{
        path: '',
        component: Home,
      },
      {
        path: '/list/:cateId',
        name: 'list',
        component: () => import("views/List"),
        meta: {},
      },
      {
        path: '/detail/:id',
        name: 'detali',
        component: () => import("views/Detail"),
        meta: {},
      },
      {
        path: "/cart",
        name: "cart",
        component: () => import("views/Cart"),
        meta: {},

      },
      {
        path: "/address",
        name: 'address',
        component: () => import("views/Address"),
        meta: {
          requiredLogin: true
        },
      },
      {
        path: "/addressEdit/:id",
        name: "addressEdit",
        meta: {
          requiredLogin: true
        },
        component: () => import("views/AddressEdit"),
      },
      {
        path: "/addressAdd",
        name: "addressAdd",
        meta: {
          requiredLogin: true
        },
        component: () => import("views/AddressAdd"),
      },
      {
        path: "/order",
        meta: {
          requiredLogin: true
        },
        name: "order",
        component: () => import("views/Order"),
      },
      {
        path: "/personal",
        name: "personal",
        meta: {
          requiredLogin: true
        },
        component: () => import("views/Personal")
      }, {
        path: "/personal/account",
        name: "account",
        meta: {
          requiredLogin: true
        },
        component: () => import("views/Account")
      },
      {
        path: "/search",
        name: "search",
        meta: {},
        component: () => import("views/Search")
      },
      {
        path: "/searchResult",
        name: "searchResult",
        meta: {},
        component: () => import("views/SearchResult")
      },
      {
        path: "/cate",
        name: "cate",
        meta: {},
        component: () => import("views/Cate")
      },
    ]
  },
]

const router = new VueRouter({
  routes
})

router.afterEach((to, from, next) => {
  // window.scrollTo(0, 0);
  // 或
  window.scroll(0, 0);
});


router.beforeEach((to, from, next) => {
  let isLogin = localStorage.getItem("user");
  if (to.fullPath == "/login" || to.fullPath == "reg") {
    next();
  } else {
    // 是否需要 登录权限
    if (to.meta.requiredLogin) {
      // 需要做验证
      if (isLogin) {
        next();
      } else {
        next("/login")
      }
    } else {
      next();
    }
  }
})


export default router